<template>
  <div>
    <div class="search">
      <el-input placeholder="请输入课程名称" style="width: 200px" v-model="name"></el-input>
      <el-select v-model="recommend" placeholder="请选择是否推荐" style="width: 200px; margin-left: 5px">
        <el-option label="是" value="是"></el-option>
        <el-option label="否" value="否"></el-option>
      </el-select>
      <el-button type="info" plain style="margin-left: 10px" @click="load(1)">查询</el-button>
      <el-button type="warning" plain style="margin-left: 10px" @click="reset">重置</el-button>
    </div>

    <div class="operation">
      <el-button type="primary" plain @click="handleAdd">新增</el-button>
      <el-button type="danger" plain @click="delBatch">批量删除</el-button>
    </div>

    <div class="table">
      <el-table :data="tableData" stripe  @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center"></el-table-column>
        <el-table-column prop="id" label="序号" width="80" align="center" sortable></el-table-column>
        <el-table-column prop="img" label="课程封面" show-overflow-tooltip>
          <template v-slot="scope">
            <div style="display: flex; align-items: center">
              <el-image style="width: 60px; height: 40px; border-radius: 10px" v-if="scope.row.img"
                        :src="scope.row.img" :preview-src-list="[scope.row.img]"></el-image>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="课程名称" show-overflow-tooltip></el-table-column>
        <el-table-column prop="content" label="内容" show-overflow-tooltip>
          <template v-slot="scope">
            <el-button type="success" size="mini" @click="viewDataInit(scope.row.content)">点击查看</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="type" label="课程类型"></el-table-column>
        <el-table-column prop="price" label="课程价格"></el-table-column>
        <el-table-column prop="video" label="课程视频" show-overflow-tooltip>
          <template v-slot="scope">
            <el-button type="warning" size="mini" @click="down(scope.row.video)" v-if="scope.row.type === 'VIDEO'">点击下载</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="file" label="课程资料" show-overflow-tooltip></el-table-column>
        <el-table-column prop="discount" label="课程折扣"></el-table-column>
        <el-table-column prop="recommend" label="是否推荐"></el-table-column>

        <el-table-column label="操作" width="180" align="center">
          <template v-slot="scope">
            <div style="display: flex; flex-direction: column; align-items: center;">
              <div style="display: flex; width: 100%;">
                <el-button plain type="primary" @click="handleEdit(scope.row)"  style=" margin-right: 5px; flex-grow: 1;">编辑</el-button>
                <el-button plain type="danger" @click="del(scope.row.id)"  style="  margin-right: 5px; flex-grow: 1;">删除</el-button>
              </div>
              <el-button plain type="info" size="mini" @click="handleEditCatalog(scope.row)" style="width: 156px; margin-top: 5px; text-align: center; padding-left: 10px; margin-right: 5px">课程目录</el-button>
            </div>
          </template>
        </el-table-column>

      </el-table>

      <div class="pagination">
        <el-pagination
            background
            @current-change="handleCurrentChange"
            :current-page="pageNum"
            :page-sizes="[5, 10, 20]"
            :page-size="pageSize"
            layout="total, prev, pager, next"
            :total="total">
        </el-pagination>
      </div>
    </div>

    <el-dialog
        title="编辑课程目录"
        :visible.sync="catalogDialogVisible"
        width="80%"
        :close-on-click-modal="false"
        destroy-on-close
    >
      <div v-if="currentCourseId">
        <el-table :data="courseCatalogData" class="ellipsis-table" style="width: 100%; margin-bottom: 20px;">

          <el-table-column prop="chapterTitle" label="章节标题" width="180"></el-table-column>
          <el-table-column prop="sectionTitle" label="子章节标题"></el-table-column>
          <el-table-column prop="content" label="内容" width="500" show-overflow-tooltip></el-table-column>
          <el-table-column prop="level" label="层级"></el-table-column>
          <el-table-column prop="sequence" label="排序"></el-table-column>
          <el-table-column prop="video" label="视频" show-overflow-tooltip></el-table-column>
          <!-- 操作列，包含编辑和可能的其他操作按钮 -->
          <el-table-column label="操作" width="150" align="center">
            <template v-slot="scope">
              <!-- 编辑按钮 -->
              <el-button type="primary" size="mini" @click="startEdit(scope.row)">编辑</el-button>
            <el-button type="danger" size="mini" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-form :model="catalogForm" :rules="catalogRules" ref="catalogFormRef">
          <el-form-item label="父母ID" prop="section_title">
            <el-input v-model="catalogForm.parent_id"></el-input>
          </el-form-item>
          <el-form-item label="章节标题" prop="chapter_title">
            <el-input v-model="catalogForm.chapterTitle"></el-input>
          </el-form-item>
          <el-form-item label="子章节标题" prop="section_title">
            <el-input v-model="catalogForm.sectionTitle"></el-input>
          </el-form-item>
          <el-form-item label="内容" prop="content">
            <el-input type="textarea" v-model="catalogForm.content"></el-input>
          </el-form-item>
          <el-form-item label="层级" prop="level">
            <el-input-number v-model="catalogForm.level" :min="0"></el-input-number>
          </el-form-item>
          <el-form-item label="排序" prop="order">
            <el-input-number v-model="catalogForm.sequence" :min="0"></el-input-number>
          </el-form-item>
          <el-form-item label="视频" prop="video">
            <el-input v-model="catalogForm.video"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="catalogDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="updateCatalogItem">更新目录</el-button>
          <el-button type="primary" @click="addCourseCatalog">添加目录</el-button>
        </span>
      </div>
    </el-dialog>


    <el-dialog title="课程信息" :visible.sync="fromVisible" width="55%" :close-on-click-modal="false" destroy-on-close>
      <el-form label-width="100px" style="padding-right: 50px" :model="form" :rules="rules" ref="formRef">
        <el-form-item label="课程封面">
          <el-upload
              class="avatar-uploader"
              :action="$baseUrl + '/files/upload'"
              :headers="{ token: user.token }"
              list-type="picture"
              :on-success="handleImgSuccess"
          >
            <el-button type="primary">上传图片</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item prop="name" label="课程名称">
          <el-input v-model="form.name" autocomplete="off" placeholder="请输入课程名称"></el-input>
        </el-form-item>
        <el-form-item prop="type" label="课程类型">
          <el-select v-model="form.type" placeholder="请选择类型" style="width: 100%">
            <el-option label="视频课程" value="VIDEO"></el-option>
            <el-option label="图文课程" value="TEXT"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="recommend" label="是否推荐">
          <el-select v-model="form.recommend" placeholder="请选择" style="width: 100%">
            <el-option label="是" value="是"></el-option>
            <el-option label="否" value="否"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="price" label="课程价格">
          <el-input v-model="form.price" autocomplete="off" placeholder="请输入价格（0表示公开课）"></el-input>
        </el-form-item>
        <el-form-item label="课程视频">
          <el-upload
              class="avatar-uploader"
              :action="$baseUrl + '/files/upload'"
              :headers="{ token: user.token }"
              :on-success="handleVideoSuccess"
          >
            <el-button type="primary">上传视频(视频课程需要传)</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item prop="file" label="资料链接">
          <el-input v-model="form.file" autocomplete="off" placeholder="请输入资料链接"></el-input>
        </el-form-item>
        <el-form-item prop="discount" label="课程折扣">
          <el-input v-model="form.discount" autocomplete="off" placeholder="请输入课程折扣"></el-input>
        </el-form-item>
        <el-form-item prop="content" label="课程介绍">
          <div id="editor"></div>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="fromVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="课程内容" :visible.sync="editorVisible" width="50%" :close-on-click-modal="false" destroy-on-close>
      <div v-html="viewData" class="w-e-text w-e-text-container"></div>
    </el-dialog>

  </div>

</template>

<script>
import E from 'wangeditor'
export default {
  name: "Course",
  data() {
    return {
      catalogForm: {
        course_id: this.currentCourseId, // 假设当前编辑的课程ID已经存在
        parent_id: '',
        chapterTitle: '',
        sectionTitle: '',
        content: '',
        level: 0,
        sequence: null,
        video: ''
      },
      catalogRules: {
        chapterTitle: [
          { required: true, message: '章节标题不能为空', trigger: 'blur' },
          { min: 1, message: '章节标题长度不能少于1个字符', trigger: 'blur' }
        ],
        sectionTitle: [
          { required: true, message: '子章节标题不能为空', trigger: 'blur' },
          { min: 1, message: '子章节标题长度不能少于1个字符', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '内容不能为空', trigger: 'blur' }
        ],
        level: [
          { required: true, message: '层级不能为空', trigger: 'blur' },
          { type: 'number', message: '层级必须为数字', trigger: 'blur' }
        ],
        sequence: [
          { required: true, message: '排序不能为空', trigger: 'blur' },
          { type: 'number', message: '排序必须为数字', trigger: 'blur' }
        ],
        video: [
          { required: true, message: '视频链接不能为空', trigger: 'blur' }
        ]
      },

      editingItem: null, // 初始化为null或空对象
      currentCourseId: null,
      courseCatalogData: [],
      catalogDialogVisible: false,
      editor: null,
      viewData: null,
      tableData: [],  // 所有的数据
      pageNum: 1,   // 当前的页码
      pageSize: 10,  // 每页显示的个数
      total: 0,
      name: null,
      recommend:null,
      fromVisible: false,
      editorVisible:false,
      form: {},
      user: JSON.parse(localStorage.getItem('xm-user') || '{}'),
      rules: {
        name: [
          {required: true, message: '请输入课程名称', trigger: 'blur'},
        ],
        type: [
          {required: true, message: '请选择课程类型', trigger: 'blur'},
        ],
        recommend: [
          {required: true, message: '请选择是否推荐', trigger: 'blur'},
        ],
        price: [
          {required: true, message: '请输入课程价格', trigger: 'blur'},
        ],
      },
      ids: []
    }
  },
  created() {
    this.load(1)
    this.fetchCourseCatalog()

  },
  methods: {
    handleEditCatalog(row) {
      this.currentCourseId = row.id;
      this.fetchCourseCatalog(this.currentCourseId);
      this.catalogDialogVisible = true;
    },

    fetchCourseCatalog(courseId) {
      this.$request.get(`/courseCatalog/getByCourseId/${courseId}`)
          .then(response => {
        if (response) {
          this.courseCatalogData = response;
        } else {
          this.$message.error('获取课程目录失败');
        }
      }).catch(error => {
        console.error('请求课程目录数据时发生错误：', error);
        this.$message.error('请求课程目录数据时发生错误');
      });
    },
    addCourseCatalog() {
      this.$refs.catalogFormRef.validate((valid) => {
        if (valid) {
          this.catalogForm.courseId = this.currentCourseId;
          this.$request({
            url: '/courseCatalog/add',
            method: 'POST',
            data: this.catalogForm
          }).then(res => {
            if (res.code === '200') {
              this.$message.success('新增目录成功');
              // 清空表单数据
              this.catalogForm = {
                // 初始化表单对象，可以根据需要设置默认值
                course_id: this.currentCourseId, // 假设这个值在添加时仍然需要保留
                parent_id: '',
                chapterTitle: '',
                sectionTitle: '',
                content: '',
                level: 0,
                sequence: null,
                video: ''
              };
              this.fetchCourseCatalog(this.currentCourseId);

            } else {
              this.$message.error(res.msg);
            }
          });
        }
      });
    },
    startEdit(row) {
      this.editingItem = JSON.parse(JSON.stringify(row)); // 深拷贝当前行数据
      this.fillForm(this.editingItem); // 将数据填充到表单
      this.catalogDialogVisible = true; // 打开编辑对话框
    },

    fillForm(item) {
      this.catalogForm = {
        course_id: item.course_id,
        parent_id: item.parent_id,
        chapterTitle: item.chapterTitle,
        sectionTitle: item.sectionTitle,
        content: item.content,
        level: item.level,
        sequence: item.sequence,
        video: item.video,
        id: item.id
      };
    },

    updateCatalogItem() {
      this.$refs.catalogFormRef.validate((valid) => {
        if (valid) {
          // 发送更新请求之前，确保所有字段都是最新的
          const updateData = {
            ...this.catalogForm,
            id: this.editingItem.id // 确保发送正确的id
          };
          this.$request({
            url: `/courseCatalog/update/${updateData.id}`,
            method: 'PUT',
            data: updateData // 发送更新的数据
          }).then(res => {
            if (res && res.code === '200') {

              this.$message.success('更新目录成功');
              this.fetchCourseCatalog(this.currentCourseId); // 重新加载课程目录数据
            } else {
              this.$message.error(res.msg || '更新失败');
            }
          }).catch(error => {
            console.error('更新课程目录数据时发生错误：', error);
            this.$message.error('更新失败，请检查控制台');
          });
        }
      });
    },

    // 处理删除操作
    handleDelete(row) {
      this.$confirm('您确定要删除这个目录项吗？', '确认删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$request.delete(`/courseCatalog/delete/${row.id}`).then(res => {
          if (res && res.code === '200') {
            this.$message.success('删除目录成功');
            this.fetchCourseCatalog(this.currentCourseId); // 刷新课程目录数据
          } else {
            this.$message.error(res.msg || '删除失败');
          }
        }).catch(error => {
          console.error('删除目录时发生错误：', error);
          this.$message.error('删除失败，请检查控制台');
        });
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },

    /*  saveCatalog() {
        this.$refs.catalogFormRef.validate((valid) => {
          if (valid) {
            this.$request({
              url: '/courseCatalog/add',
              method: 'POST',
              data: this.catalogForm
            }).then(response => {
              if (response) {
                this.$message.success('课程目录项保存成功');
                this.catalogDialogVisible = false;
                this.load(1);
              } else {
                this.$message.error(response.msg || '保存失败');
              }
            }).catch(error => {
              console.error('保存课程目录项时发生错误:', error);
              this.$message.error('服务器错误: 请稍后再试或联系管理员');
            });
          } else {
            this.$message.error('表单验证失败，请检查输入');
          }
        });
      },*/






    initWangEditor(content) {
      this.$nextTick(() => {
        this.editor = new E('#editor')
        this.editor.config.placeholder = '请输入内容'
        this.editor.config.uploadFileName = 'file'
        this.editor.config.uploadImgServer = 'http://localhost:9090/files/wang/upload'
        this.editor.create()
        setTimeout(() => {
          this.editor.txt.html(content)
        })
      })
    },
    viewDataInit(data) {
      this.viewData = data
      this.editorVisible = true
    },
    handleAdd() {   // 新增数据
      this.form = {}  // 新增数据的时候清空数据
      this.fromVisible = true   // 打开弹窗
      this.initWangEditor('')
    },
    handleEdit(row) {   // 编辑数据
      this.form = JSON.parse(JSON.stringify(row))  // 给form对象赋值  注意要深拷贝数据
      this.fromVisible = true   // 打开弹窗
      this.initWangEditor(this.form.content || '')
    },
    save() {   // 保存按钮触发的逻辑  它会触发新增或者更新
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          this.form.content = this.editor.txt.html()
          this.$request({
            url: this.form.id ? '/Course/update' : '/Course/add',
            method: this.form.id ? 'PUT' : 'POST',
            data: this.form
          }).then(res => {
            if (res.code === '200') {  // 表示成功保存
              this.$message.success('保存成功')
              this.load(1)
              this.fromVisible = false
            } else {
              this.$message.error(res.msg)  // 弹出错误的信息
            }
          })
        }
      })
    },
    del(id) {   // 单个删除
      this.$confirm('您确定删除吗？', '确认删除', {type: "warning"}).then(response => {
        this.$request.delete('/Course/delete/' + id).then(res => {
          if (res.code === '200') {   // 表示操作成功
            this.$message.success('操作成功')
            this.load(1)
          } else {
            this.$message.error(res.msg)  // 弹出错误的信息
          }
        })
      }).catch(() => {
      })
    },
    handleSelectionChange(rows) {   // 当前选中的所有的行数据
      this.ids = rows.map(v => v.id)   //  [1,2]
    },
    delBatch() {   // 批量删除
      if (!this.ids.length) {
        this.$message.warning('请选择数据')
        return
      }
      this.$confirm('您确定批量删除这些数据吗？', '确认删除', {type: "warning"}).then(response => {
        this.$request.delete('/Course/delete/batch', {data: this.ids}).then(res => {
          if (res.code === '200') {   // 表示操作成功
            this.$message.success('操作成功')
            this.load(1)
          } else {
            this.$message.error(res.msg)  // 弹出错误的信息
          }
        })
      }).catch(() => {
      })
    },
    load(pageNum) {  // 分页查询
      if (pageNum) this.pageNum = pageNum
      this.$request.get('/Course/selectPage', {
        params: {
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          name: this.name,
          recommend: this.recommend,
        }
      }).then(res => {
        this.tableData = res.data?.list
        this.total = res.data?.total
      })
    },
    reset() {
      this.name = null
      this.recommend = null
      this.load(1)
    },
    handleCurrentChange(pageNum) {
      this.load(pageNum)
    },
    handleImgSuccess(res) {
      this.form.img = res.data
    },
    handleVideoSuccess(res) {
      this.form.video = res.data
    },
    down(url) {
      location.href = url
    }
  }
}
</script>

<style scoped>
.ellipsis-table .el-table__row {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.ellipsis-table .el-table__column--selection .cell {
  padding: 0 10px;
}
</style>